﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using KPIS.GERP.Models;
using KPIS.GERP.Models.Class;
using KPIS.GERP.Models.HRM;
using KPIS.GERP.Models.SYS;
using KPIS.GERP.Models.SYS.ViewModel;
using KPIS.GERP.WEB.GIMS.Class;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class HomeController : Controller
    {
        // private SimpleMembershipInitializer simpleMembershipInitializer = new SimpleMembershipInitializer();

        public ActionResult MapAsset()
        {
            return View();
        }
        public ActionResult Index()
        {
            return View();
        }

        // [AllowAnonymous]
        public ActionResult Login()
        {
            return View();
        }

        public static List<string> LoginLog1 = new List<string>();
        // [AllowAnonymous]
        [HttpPost]
        public ActionResult Login(LoginModel model, string RememberMeChb)
        {
            System.Web.HttpContext.Current.Session["UserFilteredMenus"] = null;
            LoginLog1.Add(ControllerContext.RouteData.Values["controller"].ToString() + "/" + ControllerContext.RouteData.Values["action"].ToString()+"@"+DateTime.Now.ToString("HH:mm:ss.ff"));
            // WebSecurity.IsAuthenticated
            Session["MenuMode"] = "Main";
            model.RememberMe = (RememberMeChb == "on");
            var db = new GERPContext();
            User user;
            if (ModelState.IsValid &&
                // simpleMembershipInitializer.CheckGerpAuthenValidUserPassword(model.UserName, model.Password) &&
                ((user = db.Users.Include("Employee")
                .FirstOrDefault(o=>o.Code.ToLower().Trim() == model.UserName.ToLower().Trim().Replace("\t", "") && 
                    o.Password == model.Password)) != null))
                // WebSecurityX.Login(model.UserName, GimsMembership.WebSecurityXPassword, persistCookie: model.RememberMe))
            {
                Employee employee = user.Employee;
                //}
                if (employee == null)
                {
                    var notFoundInEmployeeExc = new Exception("Not found current employee in database");
                    ModelState.AddModelError("", notFoundInEmployeeExc.Message);
                    GimsMembership.Logout();
                    return View(model);
                }

                GimsMembership.AuditLogin(user.UserId);
                GimsMembership.Login(user.UserId);

                using (var gs = new GerpAuthenService.GerpAuthenServiceClient())
                {
                    gs.Login(employee.EmpId, GimsUtilities.ClientIp, GimsUtilities.ThisSystemId, model.UserName, employee.FullName, employee.PosId);
                } 
                return RedirectToAction("Index", "Home");
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง");
            return View(model);
        }

        // [AllowAnonymous]
        public ActionResult SingleSigon(string tokenKey, string redirectPage, bool decodeBase64 = true)
        {
            System.Web.HttpContext.Current.Session["UserFilteredMenus"] = null;
            Session["MenuMode"] = "Main";
            OTP otpData = null;
            using (var gs = new GerpAuthenService.GerpAuthenServiceClient())
            {
                var us = new UserService.UserServiceClient();
                otpData = gs.GetOTP(tokenKey);
                if (otpData == null) return Content("No data of your share key data, or data has expire or been used.");

                // Find user code
                string userCode = otpData.UserCode;
                if (string.IsNullOrWhiteSpace(userCode))
                {
                    int empId = otpData.EmpId;
                    if (empId != 0)
                    {
                        int userId = otpData.UserId;
                        if (userId != 0)
                        {
                            userCode = us.GetUsernameByUserId(ConvertUtility.ConvertOrDefaultObjectInt(userId));
                        }
                    }
                    else
                    {
                        var u = us.GetUserByEmployee(ConvertUtility.ConvertOrDefaultObjectInt(empId));
                        if (u != null)
                        {
                            userCode = u.Code;
                        }
                    }
                }

                if (string.IsNullOrWhiteSpace(userCode))
                {
                    return Content("No user key");
                }

                // this login check via usercode(citizen) and after that, GimsMembership object will get employee info.
                //if (!WebSecurityY.Login(userCode, GimsMembership.WebSecurityYPassword))
                //    return Content("Data share we got can't be login because it unauthenticated.");

                User user = us.GetUserByUserCode(userCode);

                if (user == null )
                    return Content("Can't load user of user_name = " + userCode);

                Employee employee = user.Employee;//new UserService.UserServiceClient().GetEmployeeByUser(GimsMembership.CurrentUserId);
                
                if ( employee == null) 
                    return Content("No employee of user " + userCode);


                GimsMembership.Login(user.UserId);
                gs.Login(employee.EmpId, GimsUtilities.ClientIp, GimsUtilities.ThisSystemId, userCode, employee.FullName, employee.PosId);
            }

            string url = null;

            if (!string.IsNullOrWhiteSpace(redirectPage) && decodeBase64)
                url = (Server.UrlDecode(GimsUtilities.Base64Decode(redirectPage).Replace("''N", "&").Replace("''Q", "?")));
            else if (!string.IsNullOrWhiteSpace(redirectPage))
                url = (Server.UrlDecode(redirectPage.Replace("''N", "&").Replace("''Q", "?")));
            else if(!string.IsNullOrWhiteSpace(otpData.RedirectUrl))
            {
                url = (Server.UrlDecode(otpData.RedirectUrl.Replace("''N", "&").Replace("''Q", "?")));
            }

            if(url != null) return Redirect(url);

            return RedirectToAction("Index");
        }

        // [AllowAnonymous]
        public ActionResult SingleSigonRawData(string username, string password, string redirectPage)
        {
            System.Web.HttpContext.Current.Session["UserFilteredMenus"] = null;
            Session["MenuMode"] = "Main";
            using (var gs = new GerpAuthenService.GerpAuthenServiceClient())
            {
                //if (!simpleMembershipInitializer.CheckGerpAuthenValidUserPassword(username, password) ||
                //    !WebSecurityY.Login(username, GimsMembership.WebSecurityYPassword)) return Content("Invalid authenticate.");

                User user = new UserService.UserServiceClient().GetUserByUserCode(username);
                var CurrentEmpId = user == null ? 0 : user.UserId;
                Employee employee = user != null ? user.Employee : null;

                if (user == null || employee == null)
                    return RedirectToAction("ShowSomeMessage", "Misc",
                                            new RouteValueDictionary
                                                {
                                                    {
                                                        "message", "Can't load user or employee"
                                                    }
                                                });


                GimsMembership.Login(user.UserId);
                gs.Login(CurrentEmpId, GimsUtilities.ClientIp, GimsUtilities.ThisSystemId, user.Code, employee.FullName, employee.PosId);
            }

            if (!string.IsNullOrWhiteSpace(redirectPage))
                return Redirect(Class.GimsUtilities.Base64Decode(redirectPage));

            return RedirectToAction("Index");
        }

        // [AllowAnonymous]
        public ActionResult SingleSigonCookie(string redirectPage, bool isEncode64 = true, bool contentOnly = false)
        {
            System.Web.HttpContext.Current.Session["UserFilteredMenus"] = null;
            var redirectPage1 = (redirectPage ?? "").Replace("&apos;", "'");
            if(redirectPage1.ToLower().Contains("isencode64=false"))
            {
                isEncode64 = false;
            }
            if(redirectPage1.ToLower().Contains("contentonly=true"))
            {
                contentOnly = true;
            }

            Session["MenuMode"] = "Main";
            var cookies = Request.Cookies["UserDetail"];

            int resultEmpSeq = 0;
            if (cookies != null && (cookies["EmpSeq"] == null ||
                                    !Int32.TryParse(cookies["EmpSeq"], out resultEmpSeq))) return ActionMessage("No data shared.");

            var userService = new UserService.UserServiceClient();
            User user = userService.GetUserByEmployee(resultEmpSeq); 

            if (user == null) return ActionMessage("No user shared.<br/>");

            user = userService.GetUser(user.UserId);

            //if (!WebSecurityY.Login(user.Code, GimsMembership.WebSecurityYPassword))
            //{
            //    // return ActionMessage("Invalid authenticate.");
            //    simpleMembershipInitializer.UpdateUserIfNotUseWebSecurityYPassword(user.Code);
            //    simpleMembershipInitializer.CreateUserIfNotExist(user.Code);
            //    simpleMembershipInitializer.AddUserToRole(user.Code, "Employee");
            //}
            var CurrentEmpId = user.UserId;
            Employee employee = user.Employee;

            if (employee == null)
                return ActionMessage("Can't load employee");

            GimsMembership.Login(user.UserId);

            using (var gs = new GerpAuthenService.GerpAuthenServiceClient())
            {
                gs.Login(CurrentEmpId, GimsUtilities.ClientIp, GimsUtilities.ThisSystemId, user.Code, employee.FullName, employee.PosId);
            }

            GimsUtilities.ContentOnly = contentOnly;

            if (!string.IsNullOrWhiteSpace(redirectPage) && isEncode64)
                return Redirect(GimsUtilities.Base64Decode(redirectPage));
            else if (!string.IsNullOrWhiteSpace(redirectPage))
            { 
                string url1 = Server.UrlDecode(redirectPage.Replace("''N", "&").Replace("''Q", "?").Replace("&apos;", "'")).Replace("''N", "&").Replace("''Q", "?").Replace("&apos;", "'"); 
                return Redirect(url1);
            }
            else
                return RedirectToAction("Index");


        }

        private ActionResult ActionMessage(string message)
        {
            return Content(message);
        }

        public ActionResult DevMessage()
        {
            return Content(GimsUtilities.DevMessageTestToString);
        }
        
        // Modify this code and call this action if you're want to change some permission
        // Secret
        //// [AllowAnonymous]
        //public ActionResult ChangeRoleHardCode()
        //{
        //    // user already in role, remove comment if you want to change role
        //    simpleMembershipInitializer.LoadGerpUsers();
        //    simpleMembershipInitializer._WebSecurityXUserProfiles = new UserService.UserServiceClient().GetUserProfile();
        //    simpleMembershipInitializer.ClearRole();
        //    simpleMembershipInitializer.CreateRoleIfNotExist();
        //    simpleMembershipInitializer.RemoveUserProfileIfNotExistInGerpUser();
        //    string result = "";
        //    foreach (var u in simpleMembershipInitializer._gerpUsers)
        //    {
        //        simpleMembershipInitializer.UpdateUserIfNotUseWebSecurityXPassword(u.Code);
        //        simpleMembershipInitializer.CreateUserIfNotExist(u.Code);
        //        simpleMembershipInitializer.AddUserToRole(u.Code, "Employee");
        //        result += string.Format("Add {0} to {1}<br/>", "Employee", u.Code);
        //        var citizen = u.Employee != null ? u.Employee.Citizen : null;
        //        if (u.IsAdmin)
        //        {
        //            simpleMembershipInitializer.AddUserToRole(u.Code, "Admin");
        //        result += string.Format("Add {0} to {1}<br/>", "Admin", u.Code);
        //            simpleMembershipInitializer.AddUserToRole(u.Code, "InventoryDep");
        //        result += string.Format("Add {0} to {1}<br/>", "InventoryDep", u.Code);
        //            simpleMembershipInitializer.AddUserToRole(u.Code, "PurchaseDep");
        //        result += string.Format("Add {0} to {1}<br/>", "PurchaseDep", u.Code);
        //        }
        //        else
        //        {
        //            if (citizen == "3330500816184" || citizen == "3120101305544"
        //                /* 30/4/2014 เอาออก by Ekk ตามคำร้องพี่ตอง ให้คุณกันทำคำขอแจ้งความประสงค์กับเบิกได้เหมือนพนักงานทั่วไป || citizen == "3720700401961" */)
        //            {
        //                simpleMembershipInitializer.AddUserToRole(u.Code, "InventoryDep");
        //        result += string.Format("Add {0} to {1}<br/>", "InventoryDep", u.Code);
        //                simpleMembershipInitializer.AddUserToRole(u.Code, "PurchaseDep");
        //        result += string.Format("Add {0} to {1}<br/>", "PurchaseDep", u.Code);
        //            }
        //        }
        //        if(citizen == "1100200282546")
        //        {
        //            simpleMembershipInitializer.AddUserToRole(u.Code, "HR");
        //            result += string.Format("Add {0} to {1}<br/>", "HR", u.Code);
        //        }
        //    }

        //    result += "Finished";
        //    return Content(result);

        //}

        //// [AllowAnonymous]
        //public ActionResult Dump()
        //{
        //    var db = new GERPContext(true);
        //    {
        //        for(int i = 0 ; i < 1000 ; i++)
        //        {
        //            MasContact con1 = new MasContact();
        //            con1.TaxCode = "123";
        //            con1.NameTh = "asdjf dsajfksa fs;af j ส่หฟ ่กดสากหฟ ดสกหฟ ดสาหฟ กดส่หฟ สาด่หฟ ดสาหฟีด ้สกหฟ่ดสา้หฟสา่เ้หฟวสา";
        //            con1.RecordStatus = "U";
        //            con1.ConGrpId = 1;
        //            con1.CreatedBy = 1;
        //            con1.CreatedWhen = DateTime.Now;
        //            db.MasContacts.Add(con1);
        //        }
        //        db.SaveChanges();
        //    }
        //    return Content("Fin");
        //}
        

        // [AllowAnonymous]
        public ActionResult CheckStepOrder()
        {
            string result = "";
            List<int> stepNo = new List<int>();
            var db = new GERPContext(true);
            {
                foreach (var task in db.Tasks)
                { 
                    foreach (var i in task.Simulates)
                    {
                        stepNo.Add(i.SimulateStepNo);
                    }

                    var y = task.Simulates.OrderBy(o => o.SimulateStepNo);
                    int j = 0;
                    foreach (var i in y)
                    {
                        if(i.SimulateStepNo != stepNo[j++])
                        {
                            result += (task.TaskId + "<br/>");
                            result += "<hr/>";
                            break;
                        }
                    }
                }
            }
            return Content(result);
        }



        [NonAction]
        private void _LogOff()
        {
            var user = GimsMembership.User;

            var userId = user != null ? user.UserId : 0;
            var fullName = user != null && user.Employee != null ? user.Employee.FullName : string.Empty;
            var posId = user != null && user.Employee != null ? user.Employee.PosId : 0;

            // WebSecurityX.Logout();
            GimsMembership.Logout();

            using (var gs = new GerpAuthenService.GerpAuthenServiceClient())
            {
                try
                {
                    gs.AddOrUpdateMonitor(userId, GimsUtilities.ClientIp, GimsUtilities.ThisSystemId, GimsMembership.CurrentUserName, fullName, posId, "Log out", null);
                    GimsMembership.AuditLogout();
                }
                catch (Exception exception)
                {
                    Models.Class.GerpLog.ApplicationException(exception.Message);
                }
            }
        }

        [ActionName("LogOff")]
        [HttpPost]
        public ActionResult LogOffByPost()
        {
            _LogOff();
            return _GoToEssLoginPage();
        }

        [ActionName("LogOff")]
        public ActionResult LogOffByGet()
        {
            _LogOff();
            return _GoToEssLoginPage();
        }

        public ActionResult BackToSelectSystem()
        {
            _LogOff();
            return _GoToEssSelectSystem();
        }

        [NonAction]
        private ActionResult _GoToEssSelectSystem()
        {
            string url = !string.IsNullOrWhiteSpace(GimsConfigReader.EssSelectSystemPage) ? GimsConfigReader.EssSelectSystemPage : Url.Action("Login", "Home");
            ViewBag.Url = url;
            ViewBag.Message = "กำลังกลับสู่หน้าเลือกระบบ";
            return View("_ShowSomeMessage", null);
        }

        [NonAction]
        private ActionResult _GoToEssLoginPage()
        {
            string url = !string.IsNullOrWhiteSpace(GimsConfigReader.EssLoginPage) ? GimsConfigReader.EssLoginPage : Url.Action("Login", "Home");
            ViewBag.Url = url;
            ViewBag.Message = "กำลังกลับสู่หน้าเข้าสู่ระบบ";
            return View("_ShowSomeMessage", null);
        }

        public ActionResult GenNewOtpTokenKey(string url, int height)
        {
            int userSeq = 0;
            int empSeq = 0;
            string userName = null;
            int? workingJobSiteSeq = null;
            string workingJobSiteName = null;
            int? workAreaSeq = null;
            string userCode = GimsMembership.CurrentUserName;

            try{userSeq = GimsMembership.CurrentUserId;}catch{}
            try{empSeq = GimsMembership.CurrentEmpId;}catch{}
            try{userName = GimsMembership.Employee.FullName;}catch{}
            try{workingJobSiteSeq = GimsMembership.Employee.WorkingJobSiteId;}catch{}
            try{workingJobSiteName= GimsMembership.Employee.JobSite.Name;}catch{}
            try{workAreaSeq = GimsMembership.Employee.JobSite.WorkAreaId;}catch{}
            
            string tokenKey = new GerpAuthenService.GerpAuthenServiceClient().CreateOTP(
                empSeq,
                userName,
                userSeq,
                userCode,
                height,
                workingJobSiteSeq,
                workingJobSiteName,
                workAreaSeq,
                url,
                null,
                null,
                null
                );
            return Content(tokenKey);
        }
    }
}